/**
 * 课程表主组件
 */

'use client';

import React, { useState, useMemo, useEffect } from 'react';
import { useCourseData } from '../../hooks/useCourseData';
import { useWeekCalculation } from '../../hooks/useWeekCalculation';
import { useColorAllocation } from '../../hooks/useColorAllocation';
import { useStaggeredAnimation } from '../../hooks/useStaggeredAnimation';
import { CourseCard } from './CourseCard';
import { WeekSelector } from './WeekSelector';
import { CountdownTimer } from './CountdownTimer';
import { CourseDetailModal } from './CourseDetailModal';
import { SchoolClassSelector } from './SchoolClassSelector';
import { MenuDrawer } from './MenuDrawer';
import { filterCoursesByWeek, TIME_SLOTS } from '../../utils/scheduleUtils';
import { getWeekDayHeaders, getMonthName } from '../../utils/dateUtils';
import { ProcessedCourse } from '../../types/course';
import { Menu, MessagesSquare } from 'lucide-react';
import { UUForumUrl } from '@/data/GlobalData';
import { clsx } from 'clsx';
import localStorageKeys from '../../utils/localStorageKeys';

export const CourseSchedule: React.FC = () => {
  const [selectedCourse, setSelectedCourse] = useState<ProcessedCourse | null>(null);
  const [isModalOpen, setIsModalOpen] = useState(false);
  const [isWeekSelectorOpen, setIsWeekSelectorOpen] = useState(false);
  const [isSelectorOpen, setIsSelectorOpen] = useState(false);
  const [isMenuOpen, setIsMenuOpen] = useState(false);
  const [hideWeekend, setHideWeekend] = useState(false);
  
  // 数据管理
  const {
    scheduleData,
    courses,
    loading,
    error,
    schoolId,
    classCode,
    needsSelection,
    loadCourseData,
  } = useCourseData();
  
  // 周次计算
  const {
    currentWeek,
    setCurrentWeek,
    availableWeeks,
    daysUntilEnd
  } = useWeekCalculation(
    scheduleData?.class_info.start_date || '2025-09-01',
    courses
  );
  
  // 过滤当前周的课程
  const weekCourses = useMemo(() => {
    return filterCoursesByWeek(courses, currentWeek);
  }, [courses, currentWeek]);
  
  // 颜色分配
  const { processedCourses } = useColorAllocation(weekCourses);

  // 交错动画管理
  const { animationKey, getDelay } = useStaggeredAnimation(processedCourses.length, [currentWeek]);
  
  
  // 获取当前周的日期信息
  const dayHeaders = useMemo(() => {
    if (!scheduleData) return [];
    const allHeaders = getWeekDayHeaders(new Date(scheduleData.class_info.start_date), currentWeek);
    // 如果隐藏周末,过滤掉周六和周日
    return hideWeekend ? allHeaders.filter((_, index) => index < 5) : allHeaders;
  }, [scheduleData, currentWeek, hideWeekend]);
  
  // 获取当前月份
  const currentMonth = useMemo(() => {
    if (!scheduleData) return '';
    const startDate = new Date(scheduleData.class_info.start_date);
    const currentDate = new Date(startDate);
    currentDate.setDate(currentDate.getDate() + (currentWeek - 1) * 7);
    return getMonthName(currentDate);
  }, [scheduleData, currentWeek]);
  
  // 处理课程卡片点击
  const handleCourseClick = (course: ProcessedCourse) => {
    setSelectedCourse(course);
    setIsModalOpen(true);
  };
  
  // 处理周次变化
  const handleWeekChange = (week: number) => {
    setCurrentWeek(week);
  };

  // 处理学校和班级选择
  const handleSchoolClassSelect = async (selectedSchoolId: number, selectedClassCode: string) => {
    await loadCourseData(selectedSchoolId, selectedClassCode);
  };

  // 处理切换学校
  const handleSwitchSchool = () => {
    setIsSelectorOpen(true);
  };

  // 处理隐藏周末变化
  const handleHideWeekendChange = (hide: boolean) => {
    setHideWeekend(hide);
  };

  // 当需要选择时,自动打开选择器
  useEffect(() => {
    if (needsSelection && !loading) {
      setIsSelectorOpen(true);
    }
  }, [needsSelection, loading]);

  // 从 localStorage 加载隐藏周末设置
  useEffect(() => {
    try {
      const saved = localStorage.getItem(localStorageKeys.hide_weekend);
      if (saved !== null) {
        setHideWeekend(saved === 'true');
      }
    } catch (error) {
      console.error('Failed to load hide weekend setting:', error);
    }
  }, []);
  
  // 加载状态
  if (loading) {
    return (
      <div className="min-h-screen bg-gradient-to-br from-blue-50 to-indigo-100 flex items-center justify-center">
        <div className="text-center">
          <div className="animate-spin rounded-full h-12 w-12 border-b-2 border-blue-500 mx-auto mb-4"></div>
          <p className="text-gray-600">加载课程数据中...</p>
        </div>
      </div>
    );
  }
  
  // 错误状态
  if (error) {
    return (
      <div className="min-h-screen bg-gradient-to-br from-red-50 to-pink-100 flex items-center justify-center">
        <div className="text-center">
          <p className="text-red-600 mb-4">加载课程数据失败</p>
          <p className="text-gray-600 text-sm">{error}</p>
        </div>
      </div>
    );
  }
  
  return (
    <div className="min-h-screen bg-gradient-to-br from-blue-50 to-indigo-100">
      {/* 顶部导航栏 */}
      <header className="sticky top-0 z-20 bg-white/10 backdrop-blur-md border-b border-white/20">
        <div className="container mx-auto px-4 py-3">
          <div className="flex items-center justify-between">
            {/* 左侧菜单按钮 */}
            <button 
              onClick={() => setIsMenuOpen(true)}
              className="p-2 rounded-lg text-gray-700 hover:bg-white/20 transition-colors"
            >
              <Menu className="w-6 h-6" />
            </button>
            
            {/* 中部周次选择器 */}
            <WeekSelector
              isOpen={isWeekSelectorOpen}
              onOpenChange={setIsWeekSelectorOpen}
              currentWeek={currentWeek}
              availableWeeks={availableWeeks}
              onWeekChange={handleWeekChange}
            />
             </div>
            {/* 右侧论坛按钮 */}
            <button 
              onClick={() => window.open(UUForumUrl, '_blank')}
              className="p-2 rounded-lg text-gray-700 hover:bg-white/20 transition-colors"
            >
              <MessagesSquare className="w-6 h-6" />
            </button>
            
          </div>
        </div>
      </header>
      
      {/* 课程表主体 */}
      <main className={clsx(
        "container mx-auto px-4 py-6 transition-all duration-500",
        (isWeekSelectorOpen || isModalOpen || isMenuOpen || isSelectorOpen) && "blur-sm pointer-events-none"
      )}>
        <div className="bg-white rounded-xl shadow-lg overflow-hidden">
          {/* 课程表网格 - 使用CSS Grid布局 */}
          <div 
            key={animationKey} 
            className="schedule-grid relative"
            style={{
              display: 'grid',
              gridTemplateColumns: `auto repeat(${hideWeekend ? 5 : 7}, 1fr)`,
              gridTemplateRows: 'auto repeat(6, minmax(100px, auto))',
              gap: '4px',
              padding: '16px'
            }}
          >
            {/* 第一行：表头 */}
            <div 
              className={clsx(
                "schedule-header-month bg-gray-100 rounded-lg flex items-center justify-center text-sm font-medium text-gray-700",
                "px-2 py-3 sm:px-4 sm:py-4"
              )}
              style={{ gridColumn: 1, gridRow: 1 }}
            >
              <span suppressHydrationWarning>{currentMonth}</span>
            </div>
            
            {dayHeaders.map((day, index) => (
              <div
                key={day.day}
                className={clsx(
                  'schedule-header-day rounded-lg flex flex-col items-center justify-center text-sm font-medium transition-all',
                  'py-2 sm:py-4 gap-1',
                  day.isToday
                    ? 'bg-blue-500 text-white shadow-lg'
                    : 'bg-gray-50 text-gray-700'
                )}
                style={{ gridColumn: index + 2, gridRow: 1 }}
              >
                <div className="font-semibold">{day.dayName}</div>
                <div 
                  className={clsx(
                    "text-xs",
                    day.isToday ? "opacity-90 font-medium" : "opacity-70"
                  )}
                  suppressHydrationWarning
                >
                  {day.date}
                </div>
              </div>
            ))}
            
            {/* 时间段标签 */}
            {TIME_SLOTS.map((timeSlot, rowIndex) => (
              <div
                key={`time-${timeSlot.id}`}
                className={clsx(
                  "schedule-time-slot bg-gray-100 rounded-lg flex items-center justify-center text-sm font-medium text-gray-700",
                  "px-2 sm:px-4"
                )}
                style={{ gridColumn: 1, gridRow: rowIndex + 2 }}
              >
                <span className="hidden sm:inline">{timeSlot.label}</span>
                <span className="sm:hidden time-text text-xs">
                  {timeSlot.label.split('-').map((part, index) => (
                    <React.Fragment key={index}>
                      {index > 0 && <br />}
                      {part}
                    </React.Fragment>
                  ))}
                </span>
              </div>
            ))}
            
            {/* 课程卡片 - 直接放置在Grid中 */}
            {processedCourses.map((course, index) => {
              // 如果隐藏周末且课程在周末,则不显示
              if (hideWeekend && course.day_of_week > 5) return null;
              
              const dayIndex = course.day_of_week - 1;
              const startSlotIndex = Math.floor((course.section.start - 1) / 2);
              const endSlotIndex = Math.floor((course.section.end - 1) / 2);
              const rowSpan = endSlotIndex - startSlotIndex + 1;
              
              return (
                <div
                  key={`course-${course.course_name}-${course.section.start}-${course.day_of_week}`}
                  style={{
                    gridColumn: dayIndex + 2,
                    gridRow: `${startSlotIndex + 2} / span ${rowSpan}`,
                    zIndex: 1
                  }}
                >
                  <CourseCard
                    course={course}
                    onClick={handleCourseClick}
                    animationDelay={getDelay(index)}
                  />
                </div>
              );
            })}
            
            {/* 空单元格背景 */}
            {TIME_SLOTS.map((timeSlot, rowIndex) =>
              Array.from({ length: hideWeekend ? 5 : 7 }, (_, dayIndex) => {
                const dayOfWeek = dayIndex + 1;
                const hasCourse = processedCourses.some(course => {
                  const courseStartSlot = Math.floor((course.section.start - 1) / 2);
                  const courseEndSlot = Math.floor((course.section.end - 1) / 2);
                  return course.day_of_week === dayOfWeek && 
                         rowIndex >= courseStartSlot && 
                         rowIndex <= courseEndSlot;
                });
                
                if (hasCourse) return null;
                
                return (
                  <div
                    key={`empty-${rowIndex}-${dayIndex}`}
                    className="schedule-cell rounded-lg border border-gray-200 hover:border-gray-300 transition-colors bg-white"
                    style={{
                      gridColumn: dayIndex + 2,
                      gridRow: rowIndex + 2,
                      zIndex: 0
                    }}
                  />
                );
              })
            )}
          </div>
        </div>
      </main>
      
      {/* 倒计时组件 */}
      <CountdownTimer daysRemaining={daysUntilEnd} />
      
      {/* 课程详情模态框 */}
      <CourseDetailModal
        open={isModalOpen}
        onOpenChange={setIsModalOpen}
        course={selectedCourse}
      />

      {/* 学校和班级选择弹窗 */}
      <SchoolClassSelector
        open={isSelectorOpen}
        onOpenChange={setIsSelectorOpen}
        onSelect={handleSchoolClassSelect}
        initialSchoolId={schoolId}
        initialClassCode={classCode}
      />

      {/* 菜单抽屉 */}
      <MenuDrawer
        open={isMenuOpen}
        onOpenChange={setIsMenuOpen}
        onSwitchSchool={handleSwitchSchool}
        hideWeekend={hideWeekend}
        onHideWeekendChange={handleHideWeekendChange}
      />
    </div>
  );
};
